import { Button, Drawer, Form, Input, Spin } from "antd";
import { UserSelect } from "../../components/IdSelect";
import { useAddProject, useEditProject } from "../../hooks/useProjects";
import { useForm } from "antd/lib/form/Form";
import { ErrorBox } from "../../components/ErrorBox";
import { useEffect } from "react";
import { Project } from "../../types/project";
import { useProjectModal, useProjectsQueryKey } from "./utils";
import { DrawerContainer } from "../../components/DrawerContainer";

export const ProjectDrawer = () => {
  const {
    projectModalVisible,
    closeProjectModal,
    projectToBeEdited,
    isLoading,
  } = useProjectModal();

  const title = projectToBeEdited ? "编辑项目" : "创建项目";
  const useMutateProject = projectToBeEdited ? useEditProject : useAddProject;
  const queryKey = useProjectsQueryKey();
  const {
    mutateAsync,
    error,
    isLoading: mutateLoading,
  } = useMutateProject(queryKey);
  const [form] = useForm();
  const close = () => {
    form.resetFields();
    closeProjectModal();
  };
  const handleSubmit = (values: Partial<Project>) => {
    mutateAsync({ ...projectToBeEdited, ...values }).then(() => {
      close();
    });
  };
  useEffect(() => {
    form.setFieldsValue(projectToBeEdited);
  }, [form, projectToBeEdited]);

  return (
    <Drawer
      forceRender={true}
      visible={projectModalVisible}
      onClose={close}
      width={"100%"}
    >
      <DrawerContainer>
        {isLoading ? (
          <Spin size="large" />
        ) : (
          <>
            <h1>{title}</h1>
            <ErrorBox error={error} />
            <Form
              form={form}
              onFinish={handleSubmit}
              layout="vertical"
              style={{ width: "40rem" }}
            >
              <Form.Item
                name="name"
                label="名称"
                rules={[{ required: true, message: "请输入项目名称" }]}
              >
                <Input type="text" id="name" placeholder="请输入项目名称" />
              </Form.Item>
              <Form.Item
                name="organization"
                label="部门"
                rules={[{ required: true, message: "请输入部门名称" }]}
              >
                <Input
                  type="text"
                  id="organization"
                  placeholder="请输入部门名称"
                />
              </Form.Item>
              <Form.Item name="personId" label="负责人">
                <UserSelect />
              </Form.Item>
              <Form.Item style={{ textAlign: "right" }}>
                <Button
                  htmlType="submit"
                  type="primary"
                  loading={mutateLoading}
                >
                  提交
                </Button>
              </Form.Item>
            </Form>
          </>
        )}
      </DrawerContainer>
    </Drawer>
  );
};
